package cn.pinming.config.shiro.realm;

import cn.pinming.dao.SysUserRepository;
import cn.pinming.entity.system.SysResource;
import cn.pinming.entity.system.SysRole;
import cn.pinming.entity.system.SysUser;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author wuwanggao
 */
public class DBAuthorizationRealm extends AuthorizingRealm {

    @Resource
    private SysUserRepository sysUserRepository;


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        if (username == null) {
            throw new AccountException("用户名不能为空");
        }
        SysUser user = sysUserRepository.findByUsername(username);
        if (user == null) {
            throw new UnknownAccountException("用户不存在");
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        SysUser sysUser = (SysUser) principalCollection.getPrimaryPrincipal();
        //获取该用户所拥有的角色集合
        Set<SysRole> sysRoleSet = sysUser.getSysRoleSet();
        if (CollectionUtils.isEmpty(sysRoleSet)) {
            return authorizationInfo;
        }
        for (SysRole sysRole : sysRoleSet) {
            Set<SysResource> sysResourceSet = sysRole.getSysResourceSet();
            if (CollectionUtils.isNotEmpty(sysResourceSet)) {
                for (SysResource sysResource : sysResourceSet) {
                    authorizationInfo.addStringPermission(sysResource.getPerms());
                }
            }
        }
        authorizationInfo.addRoles(sysRoleSet.stream().map(SysRole::getName).collect(Collectors.toList()));
        return authorizationInfo;
    }
}
